var divConteneurBoutons;
var sounds = new Array();

var audioDRE;

$(document).ready(function () {

    divConteneurBoutons = document.getElementById("conteneurBoutons");

    $.ajax({
        type: "GET",
        url: "sounds.xml",
        dataType: "xml",
        success: function(xml) { 
            
            // Chargement des sons
            $(xml).find('sound').each( function() {
                var sound = new Sound();
                sound.id = $(this).attr('id');
                sound.label = $(this).attr('label');
                sound.src = $(this).attr('src');
                sounds.push(sound);
            });

            // Génération des boutons
            var divLigne = '<h1>Eddy sounds</h1><div class="row show-grid">';

            for (var i = 0; i < sounds.length; i++) {
                var sound = sounds[i];
                divLigne += sound.getHtml();

                if (i + 1 % 4 == 0) {
                    divLigne += "</div>";

                    if (i < sounds.length - 1) {
                        divLigne += '<div class="row show-grid">';
                    }
                }
            }

            if (!endsWith(divLigne, "</div></div>")) {
                divLigne += "</div>";
            }

              divConteneurBoutons.innerHTML = divLigne;

            // Abonnements au clic sur les boutons
            for (var i = 0; i < sounds.length; i++) {
                var sound = sounds[i];
                $("#" + sound.id).click(function(attr) {
                    for (var j = 0; j < sounds.length; j++) {
                        var soundTemp = sounds[j];
                        if ($(this).attr('id') == soundTemp.id) {
                            startSound(soundTemp.src);
                            break;
                        }
                    };
                });
            }
            
			// player Dr DRE
			audioDRE = document.createElement('audio');
			audioDRE.setAttribute('src', "music/stillDRE.mp3");
			
			$("#playDRE").click(function(attr) {
				audioDRE.play();
			});
			
			$("#pauseDRE").click(function(attr) {
				audioDRE.pause();
			});
			
			$("#stopDRE").click(function(attr) {
				audioDRE.pause();
				audioDRE.currentTime=0;
			});
        }
    });   
});

function startSound(src) {
    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', src);
    audioElement.play();
}

function Sound() {
    this.id;
    this.label;
    this.src;

    Sound.prototype.getHtml = function() {
        return '<div class="span3"><a class="btn btn-primary btn-large" id="' + this.id + '">' + this.label + '</a></div>';
    }
}

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}